﻿using Prism.Commands;
using Prism.Mvvm;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Input;
using TiaoTiaoCode.AutoUpdate.ClientCore;
using TiaoTiaoCode.AutoUpdate.ClientCore.AutoUpdateEventArgs;
using TiaoTiaoCode.AutoUpdate.ClientUI.Models;
using TiaoTiaoCode.AutoUpdate.Common.Dtos;
using TiaoTiaoCode.Common.Extensions;

namespace TiaoTiaoCode.AutoUpdate.ClientUI.MainFrame
{
    public class MainViewModel : BindableBase
    {
        #region 字段

        readonly ClientUpgradeBootstrap _upgrade;

        #endregion

        #region 属性

        private string curVersion = default!;
        private string newestVersion = default!;
        private ObservableCollection<FileInfoModel>? files;
        private string msg = default!;
        private bool isAutoStart;

        /// <summary>
        /// 当前版本
        /// </summary>
        public string CurVersion
        {
            get { return curVersion; }
            set { SetProperty(ref curVersion, value); }
        }

        /// <summary>
        /// 最新版本
        /// </summary>
        public string NewestVersion
        {
            get { return newestVersion; }
            set { SetProperty(ref newestVersion, value); }
        }

        /// <summary>
        /// 更新文件列表
        /// </summary>
        public ObservableCollection<FileInfoModel>? Files
        {
            get { return files; }
            set { SetProperty(ref files, value); }
        }

        /// <summary>
        /// 消息
        /// </summary>
        public string Msg
        {
            get { return msg; }
            set { SetProperty(ref msg, value); }
        }

        /// <summary>
        /// 完成后是否自动启动主程序
        /// </summary>
        public bool IsAutoStart
        {
            get { return isAutoStart; }
            set
            {
                SetProperty(ref isAutoStart, value);
                _upgrade?.SetAutoStart(isAutoStart);
            }
        }

        #endregion

        #region 指令

        ICommand? closeWindowCommand;
        /// <summary>
        /// 关闭窗口
        /// </summary>
        public ICommand CloseWindowCommand => closeWindowCommand ?? (closeWindowCommand = new DelegateCommand(CloseWindow));

        #endregion

        public MainViewModel()
        {
            _upgrade = new ClientUpgradeBootstrap();
            _upgrade.OnFindAllFilesCompleted += OnFindAllFilesCompleted;
            _upgrade.OnFileDownloading += OnFileDownloading;
            _upgrade.OnFileDownloadCompleted += OnFileDownloadCompleted;
            _upgrade.OnFileAllDownloadCompleted += OnFileAllDownloadCompleted;
            _upgrade.OnException += OnException;

            _upgrade.QuickSimpleConfig();

            IsAutoStart = _upgrade.IsAutoStart;

            UpgradeVersionInfo();

            _upgrade.Startup();
        }

        #region 指令实现

        /// <summary>
        /// 启动程序并关闭自身
        /// </summary>
        void CloseWindow()
        {
            _upgrade.StartExe();

            Process.GetCurrentProcess().Kill();
        }

        #endregion

        #region 更新

        /// <summary>
        /// 版本信息
        /// </summary>
        async void UpgradeVersionInfo()
        {
            var info = await _upgrade.GetUpgradeInfo();
            if (info == null)
            {
                Msg = "未找到程序更新包信息";
                return;
            }

            CurVersion = info.CurVersion;
            NewestVersion = info.NewestVersion;
        }

        /// <summary>
        /// 自动更新异常事件
        /// </summary>
        /// <param name="args"></param>
        private void OnException(ExceptionEventArgs args)
        {
            if (args is FileDownloadExceptionEventArgs fArgs)
            {
                if (fArgs.FileId.TiaoTiaoIsNullOrEmpty())
                    Msg = fArgs.ErrMsg;
                else
                {
                    if (Files == null) return;

                    var file = Files.FirstOrDefault(t => t.FileId == fArgs.FileId);
                    if (file == null) return;

                    file.ErrMsg = fArgs.ErrMsg;
                }
            }
            else
                Msg = args.ErrMsg;
        }

        /// <summary>
        /// 自动更新全更新完毕事件
        /// </summary>
        private void OnFileAllDownloadCompleted()
        {
            Msg = "更新完成，请点击确定来启动程序";

            //if (_upgrade != null && _upgrade.IsAutoStart)
            //    CloseWindow();
        }

        /// <summary>
        /// 自动更新文件更新完成
        /// </summary>
        /// <param name="args"></param>
        private void OnFileDownloadCompleted(FileDownloadCompletedEventArgs args)
        {
            if (Files == null) return;

            var f = Files.FirstOrDefault(t => t.FileId == args.Id);
            if (f == null) return;

            f.State = Enums.FileUpgradeState.Completed;
            f.ErrMsg = "更新完成";
        }

        /// <summary>
        /// 自动更新文件更新中
        /// </summary>
        /// <param name="args"></param>
        private void OnFileDownloading(FileDownloadingEventArgs args)
        {
            if (Files == null) return;

            var f = Files.FirstOrDefault(t => t.FileId == args.Id);
            if (f == null) return;

            f.State = Enums.FileUpgradeState.Downloading;
            f.ErrMsg = "下载中...";
        }

        /// <summary>
        /// 自动更新所有更新文件已分析完
        /// </summary>
        /// <param name="files"></param>
        private void OnFindAllFilesCompleted(List<ProgrameFileDetailView> @files)
        {
            Files = new ObservableCollection<FileInfoModel>(@files.Select(t => new FileInfoModel
            {
                FileId = t.Id,
                FileName = t.FileName,
                FileVersion = t.VersionString,
                State = Enums.FileUpgradeState.Wait
            }));
        }

        #endregion
    }
}
